<template>
  <div class="card">
    <div class="card-title">
      <el-icon><histogram /></el-icon>
      信号分析图表
    </div>

    <div class="modules-container">
      <div class="chart-container" ref="scatterChart" style="height: 400px;"></div>
      <div class="chart-container" ref="freqChart" style="height: 400px;"></div>
      <div class="chart-container" ref="doaChart" style="height: 400px;"></div>
      <div class="chart-container" ref="sidChart" style="height: 400px;"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Histogram } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const props = defineProps({
  signals: {
    type: Array,
    required: true
  }
})

const scatterChart = ref(null)
const freqChart = ref(null)
const doaChart = ref(null)
const sidChart = ref(null)

let scatterInstance, freqInstance, doaInstance, sidInstance

const initCharts = () => {
  if (!scatterChart.value) return

  scatterInstance = echarts.init(scatterChart.value, 'dark')
  freqInstance = echarts.init(freqChart.value, 'dark')
  doaInstance = echarts.init(doaChart.value, 'dark')
  sidInstance = echarts.init(sidChart.value, 'dark')

  renderCharts()

  const resizeHandler = () => {
    scatterInstance.resize()
    freqInstance.resize()
    doaInstance.resize()
    sidInstance.resize()
  }

  window.addEventListener('resize', resizeHandler)

  return () => {
    window.removeEventListener('resize', resizeHandler)
  }
}

const renderCharts = () => {
  if (!props.signals.length) return

  // 时间-频率散点图
  const scatterData = props.signals.slice(0, 1000).map(s => [s.time, s.frequency, s.power])
  scatterInstance.setOption({
    title: { text: '时间-频率分布', left: 'center', textStyle: { color: '#eee' } },
    tooltip: {
      formatter: function(params) {
        return `时间: ${params.value[0].toFixed(4)}s<br>频率: ${params.value[1].toFixed(2)}MHz<br>功率: ${params.value[2].toFixed(4)}uW`
      }
    },
    grid: { top: '15%', bottom: '15%' },
    xAxis: { name: '时间(s)', nameTextStyle: { color: '#a0b0ff' } },
    yAxis: { name: '频率(MHz)', nameTextStyle: { color: '#a0b0ff' } },
    visualMap: {
      min: 0,
      max: 0.5,
      dimension: 2,
      orient: 'vertical',
      right: 10,
      top: 'center',
      text: ['高功率', '低功率'],
      calculable: true,
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    },
    series: [{
      name: '电磁信号',
      type: 'scatter',
      symbolSize: 5,
      data: scatterData
    }]
  })

  // 频率分布直方图
  const freqData = []
  for (let i = 0; i < 10; i++) {
    const lowerBound = i * 1000
    const upperBound = (i + 1) * 1000
    const count = props.signals.filter(s => s.frequency >= lowerBound && s.frequency < upperBound).length
    freqData.push(count)
  }

  freqInstance.setOption({
    title: { text: '频率分布', left: 'center', textStyle: { color: '#eee' } },
    tooltip: { trigger: 'axis' },
    grid: { top: '15%', bottom: '15%' },
    xAxis: {
      data: ['0-1000', '1000-2000', '2000-3000', '3000-4000', '4000-5000', '5000-6000', '6000-7000', '7000-8000', '8000-9000', '9000-10000'],
      axisLabel: { rotate: 45 }
    },
    yAxis: { name: '信号数量', nameTextStyle: { color: '#a0b0ff' } },
    series: [{
      name: '信号数量',
      type: 'bar',
      data: freqData,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ])
      }
    }]
  })

  // DOA分布玫瑰图
  const doaData = []
  for (let i = 0; i < 36; i++) {
    const lowerBound = i * 10
    const upperBound = (i + 1) * 10
    const count = props.signals.filter(s => s.DOA >= lowerBound && s.DOA < upperBound).length
    doaData.push({
      name: `${lowerBound}°-${upperBound}°`,
      value: count,
      itemStyle: {
        color: `hsl(${i * 10}, 70%, 50%)`
      }
    })
  }

  doaInstance.setOption({
    title: { text: 'DOA方向分布', left: 'center', textStyle: { color: '#eee' } },
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
    legend: { type: 'scroll', orient: 'vertical', right: 10, top: 20, bottom: 20 },
    series: [{
      name: 'DOA',
      type: 'pie',
      radius: ['20%', '80%'],
      center: ['40%', '50%'],
      roseType: 'area',
      data: doaData
    }]
  })

  // SID分布图
  const sidCounts = {}
  props.signals.forEach(signal => {
    sidCounts[signal.SID] = (sidCounts[signal.SID] || 0) + 1
  })

  const sidData = Object.entries(sidCounts).map(([sid, count]) => ({ value: count, name: `SID-${sid}` }))

  sidInstance.setOption({
    title: { text: '信号源分布', left: 'center', textStyle: { color: '#eee' } },
    tooltip: { formatter: '{b}: {c} 个信号 ({d}%)' },
    series: [{
      type: 'sunburst',
      data: [{
        name: '信号源',
        children: sidData
      }],
      radius: ['10%', '90%'],
      label: { rotate: 'radial' },
      levels: [{}, {
        r0: '15%',
        r: '35%',
        itemStyle: { color: '#003366' }
      }, {
        r0: '35%',
        r: '70%',
        itemStyle: { color: '#003366' }
      }, {
        r0: '70%',
        r: '72%',
        label: { position: 'outside' }
      }]
    }]
  })
}

onMounted(() => {
  initCharts()
})

watch(() => props.signals, () => {
  if (props.signals.length > 0) {
    renderCharts()
  }
})
</script>

<style scoped>
.modules-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
  gap: 25px;
}

.chart-container {
  width: 100%;
}
</style>